﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FlashGames
{
    public class Game
    {
        private static int nextId;
        public int ID { get; private set; }
        public string Name { get; set; }
        public string FileUrl { get; set; }
        public string Url { get; set; }
        public string ImageUrl { get; set; }
        public string FlashVars { get; set; }
        public Category ParentCategory { get; set; }
        public Site ParentSite { get; set; }

        public Game()
        {
            ID = Game.nextId;
            Game.nextId++;
        }

        public virtual string LoadGame()
        {
            string webData = Util.GetWebData(this.Url);

            bool found = false;
            try
            {
              Match m1 = Regex.Match(webData, this.ParentSite.GameRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
              if (this.ParentSite.GameFileRegex != null)
              {
                Match m = Regex.Match(webData, this.ParentSite.GameFileRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                while (m.Success && found == false)
                {
                  this.FileUrl = m.Groups["file"].Value;
                  string[] words = this.Name.Split(' ');
                  if (words.Any(this.FileUrl.ToLowerInvariant().Contains) && this.FileUrl.Contains(".swf"))
                  {
                    found = true;
                  }
                  m = m.NextMatch();
                }
                if (string.IsNullOrEmpty(this.FileUrl))
                  return null;
                string baseGameUrl = this.ParentSite.GameBaseUrl;
                if (string.IsNullOrEmpty(baseGameUrl))
                  baseGameUrl = this.ParentSite.Url;
                this.FileUrl = Util.ResolvedUrl(this.FileUrl, baseGameUrl);
                return this.FileUrl;
              }
            }
            catch
            {

            }
            return null;
        }

        public virtual MediaPortal.GUI.Library.GUIListItem ToGUIListItem()
        {
            MediaPortal.GUI.Library.GUIListItem Item = new MediaPortal.GUI.Library.GUIListItem();
            Item.Label = this.Name;
            Item.Path = this.Url;
            //Item.Thumbnail = this.Image;
            Item.AlbumInfoTag = this;
            return Item;
        }
    }
}
